package com.infoland.modules.orders.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXBElement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infoland.app.Constants;
import com.infoland.common.util.CniswsUtil;
import com.infoland.common.util.CommonUtil;
import com.infoland.common.util.DateUtil;
import com.infoland.modules.basic.Message;
import com.infoland.modules.members.model.ConsigneeInfo;
import com.infoland.modules.members.model.UserInfo;
import com.infoland.modules.orders.controller.OrderController;
import com.infoland.modules.orders.model.Cart;
import com.infoland.modules.orders.model.Order;
import com.infoland.modules.orders.model.OrderItem;
import com.infoland.modules.orders.service.OrderService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import ws.client.Exception_Exception;
import ws.client.ObjectFactory;
import ws.client.ThiOrderItemData;
import ws.client.ThiOrderWrap;
import ws.client.UserAudit;
import ws.client.UserAuditItem;

public class OrderServiceImpl implements OrderService {
	/**
	 * 订购 
	 * @param cart
	 * @return
	 */
	
	
	@Override
	public Message addCart(OrderController orderController) {
		Message message = new Message();
		JSONObject ob = null;
		UserInfo userInfo = (UserInfo) orderController.getSession().getAttribute(Constants.SESSION_NAME);
		String standardCode =orderController.getJSONPara("code");
		if(standardCode.contains("[") && standardCode.contains("]")){
			 String str = standardCode.replace("[", "").replace("]", "");
			 ob = JSONObject.parseObject(str);
			 System.out.println(ob);
		}else{
			ob = JSONObject.parseObject(standardCode);
			System.out.println(ob);
		}
		if(ob!=null && ob.size()>0){
			Cart cart = new Cart();
			cart.setStandardCode(ob.getString("a100"));
			cart.setStandardName(ob.getString("a298"));
			if(ob.getString("price")!=null){
				cart.setPrice(new BigDecimal(ob.getString("price")));
			}
			cart.setGoodsType(0);
			cart.setCount(Integer.valueOf(ob.getString("count")));
			cart.setFlag(0);
			cart.setFlagV("未支付");
			cart.setUserInfoId(userInfo.getId());
			cart.setIdentifier(ob.getString("a001"));
			Cart c = Cart.dao.findOneCart(userInfo.getId(),ob.getString("a100"));
			System.out.println(c);
			if(c !=null){
				c.setCount(cart.getCount()+c.getCount());
				if(c.update()){
					System.out.println(c);
					message.setMessage("加入购物车成功");
					message.setSuccess(Boolean.TRUE);
				}else{
					message.setMessage("加入购物车失败,请稍候重试");
				}
			}else{
				if(cart.save()){
					message.setMessage("加入购物车成功");
					message.setSuccess(Boolean.TRUE);
				}else{
					message.setMessage("加入购物车失败,请稍候重试");
				}
			}
		}
		return message;
	}

	/**
	 * 保存收获人地址信息 
	 * Description
	 * @param consigneeInfo
	 * @return
	 */
	@Override
	public Message saveConsignee(ConsigneeInfo consigneeInfo,Controller controller) {
		Message message = new Message();
		UserInfo userInfo = (UserInfo)controller.getSession().getAttribute(Constants.SESSION_NAME);
		Integer userId = userInfo.getId();
		if (consigneeInfo != null) {
			consigneeInfo.setUserInfoId(userId);
			if(consigneeInfo.getIsDefault()){
				ConsigneeInfo.dao.updateIsDefault(userId);
			}
			if (consigneeInfo.save()) {
				message.setMessage("保存成功");
				message.setSuccess(Boolean.TRUE);
			} else {
				message.setMessage("保存失败，请稍后再试");
			}
		}
		return message;
	}
	
	/**
	 * 单条删除订单(修改订单状态) 
	 * Description
	 * @param cart
	 * @param id
	 *            订单id
	 * @return 
	 */
	@Override
	public Message deleteOneOrder(String id) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		return message;
	}

	/**
	 * 批量删除订单(批量修改订单交易状态) Description
	 * 
	 * @param ids
	 * @return
	 */
	@Override
	@Before(Tx.class)
	public Message deleteBacthOrder(Object[] ids) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		try {
			for (Object id : ids) {
				Order.dao.deleteOrders(0, "交易关闭",id);
				
			}
			message.setMessage("删除成功，共删除  " + ids.length + " 条信息");
		} catch (Exception e) {
			e.printStackTrace();
			message.setMessage("删除失败，请稍候重试");
		}
		return message;
	}

	/**
	 * 调用中标院接口生成订单
	 * Description 
	 * @param orderList
	 * @return 
	 */
	@Override
	public Message createOrder(List<ThiOrderWrap> orderList) {
		Message message = new Message();
		String flag = "";
		// 定义订单对象
		ThiOrderWrap warp = new ThiOrderWrap();
		// 定义工厂,用于设置字段值
		ObjectFactory objFac = new ObjectFactory();
		JAXBElement<String> actualPrice = objFac
				.createThiOrderWrapActualPrice(orderList.get(0).getActualPrice().getValue());// 设置实际价格
		warp.setActualPrice(actualPrice);
		// 定义订单条目信息对象
		ThiOrderItemData thiItem = new ThiOrderItemData();
		JAXBElement<String> type = objFac.createThiOrderItemDataType("0");// 设置商品类型
		thiItem.setType(type);
		JAXBElement<String> standardUnit = objFac
				.createThiOrderItemDataA001(orderList.get(1).getItems().get(0).getA001().getValue());// 设置文献标识符
		thiItem.setA001(standardUnit);
		JAXBElement<String> standardCode = objFac
				.createThiOrderItemDataA100(orderList.get(2).getItems().get(1).getA100().getValue());// 设置文献编号
		thiItem.setA100(standardCode);
		JAXBElement<String> entityId = objFac
				.createThiOrderItemDataEntityId(orderList.get(3).getItems().get(2).getEntityId().getValue());// 设置电子全文标识
		thiItem.setEntityId(entityId);
		JAXBElement<String> unitPrice = objFac
				.createThiOrderItemDataUnitPrice(orderList.get(4).getItems().get(3).getUnitPrice().getValue());// 文献单价
		thiItem.setUnitPrice(unitPrice);
		JAXBElement<Integer> quantity = objFac
				.createThiOrderItemDataQuantity(orderList.get(5).getItems().get(4).getQuantity().getValue());// 文献数量
		thiItem.setQuantity(quantity);
		warp.getItems().add(thiItem);// 将item对象放入warp中
		try {
			flag = CniswsUtil.getCniswsbasePortType().createStandardOrder(CniswsUtil.getUserName(),CniswsUtil.getPassword(),"", "", "", warp);
		} catch (Exception e) {
				message.setMessage("订购失败,请稍候重试");
				return message;
		}
		message.setObject(flag);
		return message;
	}

	/**
	 * 调用获取订单接口 
	 * Description
	 * @param pageNumber
	 * @param pageSize
	 * @param orderCode 订单号
	 * @param orderType 订单类型
	 * @param orderState 订单状态
	 * @param startDate 下单时间起
	 * @param endDate 下单结束时间
	 * @return
	 */
	@Override
	public Message itemAuditList(Integer pageNumber, Integer pageSize, String auditId) {
		Message message  = new Message();
		message.setSuccess(Boolean.FALSE);
		List<UserAuditItem> userAuditItemList = new ArrayList<UserAuditItem>();		
		try {
			// 调用账目信息接口
			 userAuditItemList = CniswsUtil.getCniswsbasePortType().getUserAuditItem(CniswsUtil.getUserName(),CniswsUtil.getPassword(), "",
					"", "", auditId);
			
		} catch (Exception_Exception e) {
			message.setMessage("获取数据失败,请稍候重试");
			return message;
		}
		pageSize = Integer.parseInt(CniswsUtil.getPageSize());
		if (userAuditItemList != null && userAuditItemList.size() > 0) {
			Page<UserAuditItem> page = new Page<UserAuditItem>(userAuditItemList, pageNumber, pageSize, userAuditItemList.size() / pageSize,
					userAuditItemList.size());
			message.setObject(page);
		}
		return message;
	}

	/**
	 * 对账单信息
	 *  Description
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@Override
	public Message AuditList(Integer pageNumber, Integer pageSize, String relatedid, String relatedtype) {
		Message message  = new Message();
		message.setSuccess(Boolean.FALSE);
		List<UserAudit> userAuditList = new ArrayList<UserAudit>();
		try {
			// 调用对账单接口
			userAuditList = CniswsUtil.getCniswsbasePortType().getUserAuditList(CniswsUtil.getUserName(),CniswsUtil.getPassword(), "", "",
					relatedid, relatedtype, "");
		} catch (Exception_Exception e) {
			message.setMessage("数据出现异常,请稍候重试");
		}
		
		pageSize = Integer.parseInt(CniswsUtil.getPageSize());
		if (userAuditList != null && userAuditList.size() > 0) {
			Page<UserAudit> page = new Page<UserAudit>(userAuditList, pageNumber, pageSize, userAuditList.size() / pageSize, userAuditList.size());
			message.setObject(page);
		}
		return message;
	}

	/**
	 * 更新地址为默认地址
	 * Description 
	 * @param controller
	 * @return
	 */
	@Override
	public Message isDefault(Controller controller) {
		Message m = new Message();
		m.setSuccess(Boolean.FALSE);
		UserInfo userInfo = (UserInfo) controller.getSession().getAttribute(Constants.SESSION_NAME);
		Integer userId = userInfo.getId();
		Boolean b = ConsigneeInfo.dao.updateIsDefault(userId);
		if(b){
			ConsigneeInfo.dao.updateIsDefaultAddress(controller.getParaToInt(0));
			m.setMessage("设置默认地址成功");
			m.setSuccess(Boolean.TRUE);
		}else{
			m.setMessage("设置默认地址失败,请稍候重试");
		}
		return m;
	}

	/**
	 * 根据登录的用户id查询地址
	 * Description 
	 * @param userId
	 * @return
	 */
	@Override
	public List<ConsigneeInfo> findIsDefaultAddress(Integer userId) {
		return ConsigneeInfo.dao.findIsDefaultAddress(userId);
	}

	/**
	 * 删除地址
	 * Description 
	 * @param id 地址id
	 * @return
	 */
	@Override
	public Message deleteAddress(Integer id) {
		Message m = new Message();
		m.setSuccess(Boolean.FALSE);
		Boolean b = ConsigneeInfo.dao.deleteById(id);
		if(b){
			m.setMessage("删除成功");
			m.setSuccess(Boolean.TRUE);
		}else{
			m.setMessage("删除失败,请稍候重试");
		}
		return m;
	}

	/**
	 * 编辑获取地址信息
	 * Description 
	 * @param id
	 * @return
	 */
	@Override
	public ConsigneeInfo findById(Integer id) {
		return ConsigneeInfo.dao.findById(id);
	}

	/**
	 * 更新收获地址
	 * Description 
	 * @param consigneeInfo
	 * @param controller
	 * @return
	 */
	@Override
	public Message upateConsignee(ConsigneeInfo consigneeInfo, Controller controller) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		UserInfo userInfo = (UserInfo) controller.getSession().getAttribute(Constants.SESSION_NAME);
		if (consigneeInfo != null) {
			consigneeInfo.setUserInfoId(userInfo.getId());
			if(consigneeInfo.getIsDefault()){
				ConsigneeInfo.dao.updateIsDefault(userInfo.getId());
			}
			if (consigneeInfo.update()) {
				message.setMessage("修改成功");
				message.setSuccess(Boolean.TRUE);
			} else {
				message.setMessage("修改失败，请稍后再试");
			}
		}
		return message;
	}

	/**
	 * 根据登录的用户id查看购物车列表
	 * Description 
	 * @param userInfoId
	 * @return
	 */
	@Override
	public Page<Cart> cartList(Integer pageNumber,Integer pageSize,Integer userInfoId) {
		return Cart.dao.cartList(pageNumber, pageSize, userInfoId);
	}

	/**
	 * 单个/批量删除购物车列表
	 * Description 
	 * @param array
	 * @return
	 */
	@Override
	public Message deletCartById(JSONArray array) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		if (array.size()>0 ) {
			Cart.dao.deleteCartById(array);
			message.setMessage("删除成功");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("删除失败，请稍候重试");
			message.setSuccess(Boolean.FALSE);
		}
		return message;
	}

	/**
	 * 待处理订单集合
	 * Description 
	 * @param pageNumber
	 * @param pageSize
	 * @param code
	 * @param payFlagV
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Override
	public Page<Order> handleOrderList(Integer pageNumber, Integer pageSize, String code, 
			String startDate, String endDate,Integer userInfoId) {
		return Order.dao.handleOrderList(pageNumber, pageSize, code, startDate, endDate,userInfoId);
	}
	/**
	 * 已处理订单集合
	 * Description 
	 * @param pageNumber
	 * @param pageSize
	 * @param code
	 * @param payFlagV
	 * @param startDate
	 * @param endDate
	 * @return
	 */

	@Override
	public Page<Order> processedOrderList(Integer pageNumber, Integer pageSize, String code,
			String startDate, String endDate,Integer userInfoId) {
		return Order.dao.processedOrderList(pageNumber, pageSize, code, startDate, endDate,userInfoId);
	}

	/**
	 * 已废弃订单集合
	 * Description 
	 * @param pageNumber
	 * @param pageSize
	 * @param code
	 * @param payFlagV
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@Override
	public Page<Order> abandonOrderList(Integer pageNumber, Integer pageSize, String code,
			String startDate, String endDate,Integer userInfoId) {
		return Order.dao.abandonOrderList(pageNumber, pageSize, code, startDate, endDate,userInfoId);
	}

	/**
	 * 根据订单id查看订单详情
	 * Description 
	 * @param id
	 * @return
	 */
	@Override
	public List<OrderItem> findByOrderId(String orderCode) {
		return OrderItem.dao.findById(orderCode);
	}

	/**
	 * 根据订单id撤销订单(状态由待付款---已废弃)
	 * Description 
	 * @param id 订单id
	 * @return
	 */
	@Override
	public Message cancleOrder(String orderCode) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		Order order = Order.dao.findByOrderCode(orderCode);
		List<OrderItem> itemList = OrderItem.dao.findByMainOrderId(orderCode);
		if(order != null){
			order.setFlag(0);
			order.setFlagV("交易关闭");
			order.setPayFlag(2);
			order.setPayFlagV("已废弃");
			for(OrderItem item:itemList){
				item.setPayFlag(2);
				item.setPayFlagV("已废弃");
				item.update();
			}
			if(order.update()){
				message.setMessage("撤销订单成功");
				message.setSuccess(Boolean.TRUE);
			}else{
				message.setMessage("撤销订单失败");
			}
		}
		return message;
	}

	/**
	 * 提交订单
	 * Description 
	 * @param cart
	 * @return
	 */
	@Override
	@Before(Tx.class)
	public Message saveOrder(OrderController controller) {
		Message message = new Message();
		String cId = controller.getJSONPara("cId");//收货地址id
		UserInfo info = (UserInfo) controller.getSession().getAttribute(Constants.SESSION_NAME);
		JSONArray array = controller.getJSONArray("record");
		for(int i=0;i<array.size();i++){
			String mainCode = new StringBuffer().append("Mzby").append(DateUtil.getTimestamp())
					.append(CommonUtil.nextval("main_order_no")).toString();
			String itemCode = new StringBuffer().append("zby").append(DateUtil.getTimestamp())
					.append(CommonUtil.nextval("sub_order_no")).toString();
			JSONObject object = array.getJSONObject(i);
			if(StrKit.notBlank(object.getString("id"))){
				if(object!=null){
					Order order = new Order();
					order.setOrderCode(mainCode);
					order.setOrderDate(new Date());
					order.setItemCount(Integer.valueOf(object.getString("count")));
					if(StrKit.notBlank(object.getString("price"))){
						order.setTotalAmount(BigDecimal.valueOf(Double.valueOf(object.getString("price"))).multiply(BigDecimal.valueOf(Double.valueOf(object.getString("count")))));
					}else{
						order.setTotalAmount(BigDecimal.valueOf(0));
					}
					order.setFlag(1);
					order.setFlagV("交易中");
					order.setPayFlag(0);
					order.setPayFlagV("未支付");
					if(info!=null){
						order.setUserInfoId(info.getId());
						order.setUserName(info.getUserName());
					}
					if(StrKit.notBlank(cId)){
						order.setConsigneeId(Integer.parseInt(cId));
					}
					OrderItem item = new OrderItem();
					order.save();
					item.setItemCode(itemCode);
					item.setOrderCode(mainCode);
					item.setCreateTime(new Date());
					if(StrKit.notBlank(object.getString("price"))){
						item.setStandardPrice(BigDecimal.valueOf(Double.valueOf(object.getString("price"))));
					}else{
						item.setStandardPrice(BigDecimal.valueOf(0));
					}
					item.setStandardCount(Integer.valueOf(object.getString("count")));
					item.setStandardCode(object.getString("standard_code"));
					item.setStandardName(object.getString("standard_name"));
					item.setPayFlag(0);
					item.setPayFlagV("未支付");
					item.setPaymentTime(new Date());
					item.setRefundFlag(false);
					item.setRefundFlagV("无退款");
					item.setStandardIdentifier(object.getString("identifier"));
					if(info!=null){
						item.setUserInfoId(info.getId());
						item.setUserName(info.getUserName());
						if(item.save()){
							message.setMessage("提交订单成功");
							message.setSuccess(Boolean.TRUE);
						}else{
							message.setMessage("提交订单失败,请稍候重试");
						}
					}
				}
				
			}else{
				JSONArray json = controller.getJSONArray("record");	
				if(json!=null && json.size()>0){
					JSONObject record = json.getJSONObject(0);
					if(record!=null){
						OrderItem item = new OrderItem();
						Order order = new Order();
						order.setOrderCode(mainCode);
						order.setOrderDate(new Date());
						order.setItemCount(Integer.parseInt(record.getString("count")));
						if(StrKit.notBlank(record.getString("price"))){
							order.setTotalAmount(new BigDecimal(record.getString("price")));
						}
						order.setFlag(1);
						order.setFlagV("交易中");
						order.setPayFlag(0);
						order.setPayFlagV("未支付");
						if(info!=null){
							order.setUserInfoId(info.getId());
							order.setUserName(info.getUserName());
						}
						if(StrKit.notBlank(cId)){
							order.setConsigneeId(Integer.parseInt(cId));
						}
						order.save();
						item.setItemCode(itemCode);
						item.setOrderCode(mainCode);
						item.setCreateTime(new Date());
						item.setStandardPrice( new BigDecimal(record.getString("price")));
						item.setStandardCount(Integer.parseInt(record.getString("count")));
						item.setStandardCode(record.getString("a100"));
						item.setStandardName(record.getString("a298"));
						item.setStandardIdentifier(record.getString("a001"));
						item.setPayFlag(0);
						item.setPayFlagV("未支付");
						item.setPaymentTime(new Date());
						item.setRefundFlag(false);
						item.setRefundFlagV("无退款");
						if(info!=null){
							item.setUserInfoId(info.getId());
							item.setUserName(info.getUserName());
							if(item.save()){
								message.setMessage("提交订单成功");
								message.setSuccess(Boolean.TRUE);
							}else{
								message.setMessage("提交订单失败,请稍候重试");
							}
						}
					}
				}
				
			}
		}
		return message;
	}

	/**
	 * 根据用户id和数据id查询购物车某条数据
	 * Description 
	 * @param userInfoId
	 * @param cartId
	 * @return
	 */
	@Override
	public Cart findOneCart(Integer userInfoId,String standardCode) {
		return Cart.dao.findOneCart(userInfoId, standardCode);
	}
}
